package com.ai;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageSplitter {
    /**
     * 将图片分割成小块
     * @param sourceImagePath 源图片路径
     * @param outputDir 输出目录
     * @param rows 需要分割的行数
     * @param cols 需要分割的列数
     * @throws IOException IO异常
     */
    public void splitImage(String sourceImagePath, String outputDir, int rows, int cols) throws IOException {
        // 读取源图片
        File sourceFile = new File(sourceImagePath);
        BufferedImage sourceImage = ImageIO.read(sourceFile);
        
        // 计算每个小块的宽度和高度
        int chunkWidth = sourceImage.getWidth() / cols;
        int chunkHeight = sourceImage.getHeight() / rows;
        
        // 确保输出目录存在
        File dir = new File(outputDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 分割图片
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                // 计算当前小块的位置
                int x = j * chunkWidth;
                int y = i * chunkHeight;
                
                // 创建小块图片
                BufferedImage chunk = sourceImage.getSubimage(x, y, chunkWidth, chunkHeight);
                
                // 保存小块图片
                String fileName = String.format("chunk_%d_%d.png", i, j);
                File outputFile = new File(dir, fileName);
                ImageIO.write(chunk, "png", outputFile);
            }

        }
    }


    public static void main(String[] args) {
        try {
            ImageSplitter splitter = new ImageSplitter();
            splitter.splitImage(
                    "C:\\Users\\admin\\Desktop\\card\\card-2.png",  // 源图片路径
                    "C:\\Users\\admin\\Desktop\\card\\card",  // 输出目录
                    5,  // 分割成3行
                    13   // 分割成3列
            );
            System.out.println("图片分割完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

} 